﻿using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Runtime.InteropServices;
using System.Text;
using System.Threading.Tasks;

namespace WJ.Infrastructure.Windows
{
    public class WindowsUtil
    {
        #region 获取硬盘序列号

        [DllImport("DiskID32.dll")]
        public static extern long DiskID32(ref byte DiskModel, ref byte DiskID);

        /// <summary>
        /// 获取硬盘序列号
        /// </summary>
        /// <returns></returns>
        public string GetDiskID()
        {

            byte[] DiskModel = new byte[31];
            byte[] DiskID = new byte[31];
            int i;
            string ID = "";

            if (DiskID32(ref DiskModel[0], ref DiskID[0]) != 1)
            {

                for (i = 0; i < 31; i++)
                {

                    if (Convert.ToChar(DiskID[i]) != Convert.ToChar(0))
                    {
                        ID = ID + Convert.ToChar(DiskID[i]);
                    }
                }
                ID = ID.Trim();
            }

            return ID;
        }
        #endregion

        #region 判断网络连接是否连接
        [DllImport("wininet.dll")]
        private extern static bool InternetGetConnectedState(out int connectionDescription, int reservedValue);
        /// <summary>
        /// 当前网络连接状态

        /// </summary>
        /// <returns>当为true时，网络正常;当为false时，网络断开</returns>
        public bool IsConnected()
        {
            int I = 0;
            bool state = InternetGetConnectedState(out I, 0);
            return state;
        }
        #endregion

        #region 判断与某服务器是否连接

        /// <summary>
        /// 测试与指定服务器是否正常连接
        /// </summary>
        /// <param name="strIp"></param>
        /// <returns></returns>
        public string CmdPing(string strIp)
        {
            Process p = new Process();
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardInput = true;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.RedirectStandardError = true;
            p.StartInfo.CreateNoWindow = true;
            string pingrst;
            p.Start();
            p.StandardInput.WriteLine("ping -n 1 " + strIp);
            p.StandardInput.WriteLine("exit");
            string strRst = p.StandardOutput.ReadToEnd();
            if (strRst.IndexOf("(0% loss)") != -1)
                pingrst = "连接";
            else if (strRst.IndexOf("Destination host unreachable.") != -1)
                pingrst = "无法到达目的主机";
            else if (strRst.IndexOf("Request timed out.") != -1)
                pingrst = "超时";
            else if (strRst.IndexOf("Unknown host") != -1)
                pingrst = "无法解析主机";
            else
                pingrst = strRst;
            p.Close();
            return pingrst;
        }

        #endregion
    }
}
